package com.tastesport.chat.util.task;

import com.tastesport.chat.service.RedpacketService;
import com.tastesport.chat.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
@Configurable
public class RedpacketTimedtask {

    @Autowired
    RedpacketService rpService;

    @Autowired
    RedisUtil redis;
    @Value("${custom-attr.redis.rootname}")
    String redisRoot;

    @Scheduled(cron = "0 0 */1 * * ?")
    public void task() {
        System.out.println("task定时任务 .. 过期红包清理");
        Set<String> redpacketSet = redis.keys(redisRoot + ":redpacket:send*");
        for (String key : redpacketSet) {
            Map<String, Object> rp = (HashMap<String, Object>) redis.get(key);
            // 过期红包的处理
            if (new Date().getTime() > (Long) rp.get("expire_time")) {
                outofdateManage(key, rp);
                System.out.println("过期红包清理完成");
            }
        }
    }

    // 处理过期红包
    private boolean outofdateManage(String key, Map<String, Object> rp) {
        String[] redisKey = key.split(":");
        String rp_id = redisKey[redisKey.length - 1];
        Integer redpacket_id = Integer.parseInt(rp_id);
        // 返还金额
        rpService.changeMoney((String) rp.get("user_id"), (BigDecimal) rp.get("remain_money"));
        // 标记过期
        rpService.setState(redpacket_id, 3);
        // 清理redis缓存
        redis.del(redisRoot + ":redpacket:send:" + redpacket_id);
        redis.del(redisRoot + ":redpacket:tryopen:" + redpacket_id);
        return true;
    }
}
